package com.gxwgy.wg2404.controller;

import com.gxwgy.wg2404.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 姚相国
 * @version 1.0
 * @className GetEventInfo  返回剩余名额和当前报名人数 拼成json发送给list
 * @date 2024/12/18 01:39
 */
@WebServlet({"/GetEventInfo"})
public class GetEventInfoServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String eventId = request.getParameter("eventId");
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();

            // 获取活动的剩余名额和当前报名人数
            String sql = "SELECT capacity, (SELECT COUNT(*) FROM enrollments WHERE event_id = ?) AS enrolled FROM events WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, eventId);
            stmt.setString(2, eventId);
            rs = stmt.executeQuery();

            if (rs.next()) {
                int capacity = rs.getInt("capacity");
                int enrolled = rs.getInt("enrolled");
                int remainingSpots = capacity - enrolled;

                // 返回剩余名额和当前报名人数
                response.setContentType("application/json");
                response.getWriter().write("{\"remainingSpots\": " + remainingSpots + ", \"currentEnrollment\": " + enrolled + "}");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, rs);
        }
    }
}

